package com.aote.expression.paramprocessor;
import java.lang.reflect.Method;
import java.util.Map;

import com.aote.expression.Param;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.tools.BSCalendar;
import com.browsesoft.user.User;

public class DateProcessor implements ParamProcessor {

	public String process(Param param, Map attribures, User loginUser,
			HTMLBasicComponent component) {
		BSCalendar b = this.getBSCalendar(param,attribures);
		if(b==null)return"";
		String format = (String) param.getParams().get("format");
		if (format == null) {
			return b.toString();
		}
		// 返回回当前第几周
		else if (format.equals("weekofyear")) {
			return b.getWeekOfYear() + "";
		} else if (format.equals("weekofmonth")) {
			return b.getWeekOfMonth() + "";
		}
		// 返回当前周的第一天的日期
		else if (format.equals("weekfirstday")) {
			return b.getFirstDayOfWeek() + "";
		}
		// 返回当前周的最后一天日期
		else if (format.equals("weekendday")) {
			return b.getEndDayOfWeek() + "";
		} 
		//返回月第一天日期
		else if(format.equals("monthfirstday"))
		{
			return b.getFirstDayOfMonth()+"";
		}
		//放回月最后一天日期
		else if(format.equals("monthendday"))
		{
			return b.getEndDayOfMonth()+"";
		}
		else {
			return b.toString(format);
		}
	}

	/**
	 * 根据参数得到新日期
	 */
	/**
	 * @param movemethod
	 * @param num
	 * @return
	 */
	private BSCalendar getBSCalendar(Param param,Map attribures) {
		try {
			String field = (String)param.getParams().get("field");
			BSCalendar t = null;
			if(field!=null){
				String time = (String)attribures.get(field);
				String format = (String) param.getParams().get("format");
				if(time==null)return null;
				t = new BSCalendar(time,format);
			} else {
				t = BSCalendar.now();
			}
			String dateAttr = (String) param.getParams().get("dateattr");
			if(dateAttr != null && !dateAttr.equals(""))
			{
				String v = (String)attribures.get(dateAttr);
				t = new BSCalendar(v);
			}
			String movemethod = (String) param.getParams().get("movemethod");
			String num = (String) param.getParams().get("num");
			if (movemethod == null || num == null) {
				return t;
			}
			Class c = Class.forName("com.browsesoft.tools.BSCalendar");
			Class[] p = new Class[1];
			p[0] = Integer.TYPE;
			Method ms = c.getMethod(movemethod, p);
			Object[] obj = new Object[1];
			obj[0] = new Integer(num);
			BSCalendar result = (BSCalendar) ms.invoke(t, obj);
			//第二个方法
			String twomethod = (String)param.getParams().get("twomethod");
			String twonum = (String)param.getParams().get("twonum");
			if(twomethod ==null || twonum == null){
				return result;
			}
			ms = c.getMethod(twomethod, p);
			obj = new Object[1];
			obj[0] = new Integer(twonum);
			result = (BSCalendar) ms.invoke(result, obj);
			
			return result;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
